//
//  NetworkTools.m
//  OCMicroBlog
//
//  Created by 002 on 15/11/4.
//  Copyright © 2015年 002. All rights reserved.
//

#import "NetworkTools.h"
#import "SVProgressHUD.h"
#import "UserAccountViewModel.h"

@interface NetworkTools ()<NetworkToolsProxy>

@end

@implementation NetworkTools

static NSString *appKey = @"3181028143";
static NSString *appSecret = @"2c595abe4d4f8d711ccf9feee0f0b1ad";
static NSString *redirectUri = @"https://www.baidu.com";

/**
 *  单例接口
 *
 *  @return sharedTools
 */
+(instancetype)sharedTools {
    
    static NetworkTools *_instance;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        _instance = [[NetworkTools alloc] init];
        
        _instance.responseSerializer.acceptableContentTypes = [_instance.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        _instance.responseSerializer.acceptableContentTypes = [_instance.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    });
    return _instance;
}

/**
 *  网络请求方法
 *
 *  @param method     请求方式
 *  @param URLString  请求地址
 *  @param parameters 请求参数
 *  @param finished   完成回调
 */
- (void)request:(HFHRequsetMethod)method URLString:(NSString *)URLString parameters:(id)parameters finished:(RequestCallBack)finished {
    
    NSAssert(finished != nil, @"必须输入完成回调");
    
    NSString *methodName = (method == GET) ? @"GET" : @"POST";

    // 必须 resume
    [[self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {

//        [SVProgressHUD showInfoWithStatus:@"正在玩命加载中" maskType:SVProgressHUDMaskTypeGradient];
        finished(responseObject,nil);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"%@",error);
        finished(nil,error);
    }] resume];
    
}

#pragma mark - 加载用户信息
/**
 *  加载用户信息
 *
 *  @param uid         uid
 *  @param accessToken accessToken
 *  @param finished    完成回调
 */
- (void)loadUserInfoWithUID:(NSString *)uid finished:(RequestCallBack)finished {
    
    NSString *urlString = @"https://api.weibo.com/2/users/show.json";
    
    // 1. 判断字典是否为空
    NSMutableDictionary *params = [UserAccountViewModel sharedAccountViewModel].tokenDict;
    if (!params) {
        finished(nil,[[NSError alloc] initWithDomain:@"cn.itheima.error" code:-1001 userInfo:@{@"message" : @"字典为空"}]);
        return;
    }
    
    // 2. 拼接请求参数
    [params setObject:uid forKey:@"uid"];
    
    NSLog(@"params:%@",params);
    
    // 3. 发送网络请求
    [self request:GET URLString:urlString parameters:params finished:finished];
}

#pragma mark - 加载微博数据
/**
 *  加载微博数据
 *
 *  @param since_id 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
 *  @param max_id   若指定此参数，则返回ID小于或等于max_id的微博，默认为0
 *  @param finished  完成回调
 */
- (void)loadStatus:(NSUInteger) since_id max_id:(NSUInteger)max_id finished:(RequestCallBack)finished {
    
    // 1. 如果字典为 nil，通知调用方，token 无效
    NSMutableDictionary *params = [UserAccountViewModel sharedAccountViewModel].tokenDict;
    if (!params) {
        finished(nil,[[NSError alloc] initWithDomain:@"cn.itheima.error" code:-1001 userInfo:@{@"message" : @"字典为空"}]);
        return;
    }
    
    if (since_id > 0) {
        [params setObject:@(since_id) forKey:@"since_id"];
    } else if (max_id > 0) {
        [params setObject:@(max_id) forKey:@"max_id"];
    }
    
    // 2. 处理网络参数
    NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    // 3. 发起网路请求
    [self request:GET URLString:urlString parameters:params finished:finished];
}

#pragma mark - 加载 Token
- (void)loadAccessTokenWithCode:(NSString *)code finished:(RequestCallBack)finished {
    
    NSString *urlString = @"https://api.weibo.com/oauth2/access_token";
    
    NSDictionary *params = @{@"client_id": appKey,
                             @"client_secret": appSecret,
                             @"grant_type": @"authorization_code",
                             @"code" : code,
                             @"redirect_uri": redirectUri};

    [self request:POST URLString:urlString parameters:params finished:finished];
}

#pragma mark - OAuth 相关方法和属性
- (NSURL *)oauthUrl {
    if (!_oauthUrl) {
        
        NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",appKey,redirectUri];

        _oauthUrl = [NSURL URLWithString:urlString];
    }
    return _oauthUrl;
}

@end
